// Copyright (c) 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.


Array.prototype.remove = function(value) {
	if (this.indexOf(value)!==-1) {
		this.splice(this.indexOf(value), 1);
		return true;
	} else {
		return false;
	};
} 

angular.module("APP", [])

.config(function($provide, $httpProvider) {
	$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
	$httpProvider.defaults.withCredentials = true;
	/**
	 * ajax 拦截器。
	 */
	$provide.factory('httpInterceptor', function($q) {
		var baseUrl = "http://www.txiaoyuan.cn/index/t.php";
		return {
			request: function(cfig) {
				var url = cfig.url;
				cfig.cache = false;
				if(cfig.baseUrl) {
					if(url && url.substring(0, 1) == "/") {
						url = url.substring(1);
					}
					cfig.url = baseUrl + url;
				}

				return cfig;
			}
		};
	});
	$httpProvider.interceptors.push('httpInterceptor');
})

.controller("appController", ["$scope", "$http", "$filter", function($scope, $http, $filter) {
	$scope.boxs = {};
	$http({
		url:"?m=Admin&c=ApiBox&a=getBoxBySchool",
		method:"get",
		baseUrl:true
	}).success(function(data){
		if(data.code!=0){
			var boxList = data.data.box_list;
			for(var i in boxList){
				$scope.boxs[boxList[i].box_id] = boxList[i].name;
			}
		}
	})
	
	/**
	 * 获取订单
	 */
	$scope.unLogin = false;
	$http({
		url:"?m=Admin&c=ApiSchool&a=getOrderList",
		method:"post",
		baseUrl:true,
		params:{
			status:1,
			count:50,
			page:1
		}
	}).success(function(data){
		if(data.code!=0){
			$scope.orders = data.data;
		} else {
			$scope.unLogin = true;
		}
	});
	
	$scope.goToAdmin = function(){
		chrome.tabs.create({url: "http://www.txiaoyuan.cn/ht_user/"});
	}
	
	$scope.goToOrder = function(){
		chrome.tabs.create({url: "http://www.txiaoyuan.cn/ht_user/order.html"});
	}
	
	$scope.confirm = function(){
		
	}
	
	$scope.login = function(){
		chrome.tabs.create({url: "http://www.txiaoyuan.cn/"});
	}
	
	$scope.confirmOrder = function(order){
		$http({
			url:"?m=Admin&c=ApiOrder&a=setOrderDeliver",
			method:"post",
			data:"order_id="+order.order_id,
			baseUrl:true
		}).success(function(data){
			if(data.code==200){
				$scope.orders.remove(order);
				layer.msg('订单已处理');
			}
		});
	}
}])